package com.yeskery.nut.websocket.netty;

import com.yeskery.nut.websocket.WebSocketServerConfigure;
import com.yeskery.nut.websocket.BaseWebSocketServerConfigureSession;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.nio.ByteBuffer;

/**
 * Netty WebSocket会话包装对象
 * @author sprout
 * @version 1.0
 * 2023-04-22 14:07
 */
public class NettyWebSocketSession extends BaseWebSocketServerConfigureSession {

    /** 通道处理上下文 */
    private final ChannelHandlerContext channelHandlerContext;

    /**
     * 构建Netty WebSocket会话包装对象
     * @param channelHandlerContext 通道处理上下文
     * @param decoder 查询解码器
     * @param webSocketServerConfigure WebSocket服务端配置项对象
     */
    public NettyWebSocketSession(ChannelHandlerContext channelHandlerContext, QueryStringDecoder decoder, WebSocketServerConfigure webSocketServerConfigure) {
        super(decoder.path(), decoder.parameters(), webSocketServerConfigure);
        this.channelHandlerContext = channelHandlerContext;
    }

    @Override
    public String getId() {
        return channelHandlerContext.channel().id().asLongText();
    }

    @Override
    public Object getOriginalSession() {
        return channelHandlerContext;
    }

    @Override
    public void sendText(String text) {
        channelHandlerContext.writeAndFlush(new TextWebSocketFrame(text));
    }

    @Override
    public void sendBinary(ByteBuffer data) {
        channelHandlerContext.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(data)));
    }

    @Override
    public void sendBytes(byte[] bytes) {
        channelHandlerContext.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(bytes)));
    }

    @Override
    public void close() {
        channelHandlerContext.close();
    }
}
